Home |
| Latest | About | Random
# Week 1 Wednesday Dear Class, We are starting **section 5** and hopefully before end of next Monday we will have finished section 5. It is a long section so let's get started. As always, always **RTB**! **Don't forget HW0 due tonight at 10 pm. And note you have unlimited tries before the deadline!** **Today I really want to get through**: type, declaring and defining a variable, assignment `=`, `int` and its operations `+`, `-`, `*`, `+=`, `-=`, `*=`, `++`, `--`, `/`, `%`, `/=` and `%=`. **We'll draw some diagrams today, get pencil/paper ready!** Some addendum. - Last time we mentioned this "C++ Standards", which is like a rule book for all things C++, you can find them here: [https://cppreference.com/](https://cppreference.com/). Though it is *unofficial*, it is quite decent. The official place to find the official standard is at [https://isocpp.org/std/the-standard](https://isocpp.org/std/the-standard), but it is highly technical. - We also mentioned machine code. Here's a cool old book [[1-teaching/ucla-2026-fall-pic-10a/---files/machine-code-for-beginners.pdf|machine-code-for-beginners]] describing how machine code works on *older* machines using the Z80 or 6502 microprocessors. - **A propaganda for text editors and terminal commands. Only read this if you are a rad rebel and not afraid of trouble:** [[1-teaching/ucla-2026-fall-pic-10a/text-editor-and-terminal|text-editor-and-terminal]] Ok, we resume our regularly scheduled programming... -- B. ## Types. "Everything" in C++ has a **type**. - The string literal `"Hello"` has type `const char[6]`. Yes `6`. As it turns out string literals is an array of of characters plus an implicit null-terminating character `\0`. But we won't worry about this until later. - The string literal `"Joy to the world"` has type `const char[17]`. - What do you think the type of the string literal `"Q"` is? How about the string literal `""`? - Even `std::cout` has a type, its type is `std::ostream`. - And `std::endl` has type that is a function (of some signature, we come back to this). Here are some simpler examples. These are some **fundamental types** (basic types built into the C++ language, later we see we can make our own types): - `int` for integers, like `4`, `-2`, `0`, `137`, etc. It has a limited range, however. - `double` for decimal numbers, like `0.5`, `0.25`, `2.0`. It has a limited range, however. - `char` for characters, like `'3'`, `'a'`, `'Q'`, `'\n'`. Note the single-quotes. A `char` is exactly 1 byte = 8 bit, and there are exactly $2^{8} = 256$ of these. More on this later. - `bool` for Boolean values. There are exactly two, namely `true` or `false`. **Note.** These fundamental types, along with string literals, can also be "gobbled up" by `cout`, so you can use `cout` to print them to the console as usual! ## Variables. To really write useful program, we make use of **variables**, that allows us (1) to **store a value,** (2) **update the value** (if the variable is not a `const` variable), and (3) we can give them **descriptive names** to refer to useful values later. So how do we create them? ### Declare and define. Since everything in C++ has a type, so do variables. To **declare and define** a variable called `X` of type `T` we write `T X;` . The proper C++ parlance for a "name" of a variable is **identifier**. So `X` is an identifier, but calling it a name is fine. If we want to declare and define variables with names `X`, `Y`, and `Z` to be all of the same type `T` we can do this in one statement as `T X, Y, Z;`. This has the same effect as `T X; T Y; T Z;`. Let us take `int` as an example. Say we want to declare and define a variable called `i` of type `int`. Then we write `int i;`. What this does is it tells the compiler to 1. reserve enough memory for an `int`, and that 2. the name `i` will be used to access and modify the value at that place in memory. The C++ term for "name" of a variable is **identifier**. Note, there is a slight distinction between declaring and defining, but for now for our purpose, it is ok to use them interchangeably. We diagrammatically represent the statement `int i;` as follows: Draw a box to represent the amount of memory reserved for an `int` and write `i` next to it. ![[1-teaching/ucla-2026-fall-pic-10a/---files/int_i.png]] We can also declare and define several variables of the same types at once, like so `int i, j, k;` and diagrammatically we can draw something like this ![[1-teaching/ucla-2026-fall-pic-10a/---files/int_i,j,k.png]] Great, but what value does `i` hold currently? Well it currently has a *garbage value* (whatever value that memory is pointing at currently), and if we try to print it out with `cout`, it is an **undefined behavior (UB)**! Try this on different IDEs or compilers: ```cpp #include using namespace std; int main(){ int i; // declares and defines a variable called i of type int cout << i; return 0; } ``` OnlineGDB, XCode, VS may give different behaviors! In above situation, we say `i` is an *uninitialized variable*, we haven't assign to it a value. Using an uninitialized `int` gives undefined behavior. (Note. Some *other* types *may* have a default initialized value, but `int` does not.) Now to **assign** a value to `i`, we use the `=` operator. In general if we want to assign the value `V` to the variable `X`, we write `X = V`. ```cpp #include using namespace std; int main(){ int i; // declares and defines a variable called i of type int i = 7; // the value 7 is assigned to the variable called i cout << i; // this now will correctly print out 7 return 0; } ``` So this compound statement `int i; i = 7;` means 1. create enough memory for an `int`, 2. tell the compiler the name `i` will be used to access and modify the value at this memory, and 3. assign the value `7` to this memory. Diagrammatically, `i = 7` puts the value `7` into the box that represent the memory associated to the name (identifier) `i`. ![[1-teaching/ucla-2026-fall-pic-10a/---files/int_ieq7.png]] We often declare, define, and initialize a variable all at once, by writing `int i = 7;`. Doing this is called _initialization_. Note in above `cout << i` prints out the value held by `i`, and not the string literal `"i"`! **Build-Error.** You cannot use a variable before declaring it. Below are two errors, find them and explain. ```cpp int main(){ i = 7; return 0; } ``` ```cpp int main(){ i = 7; int i; return 0; } ``` **Build-Error.** You **cannot** re-define a variable. This is a redefinition error. ```cpp int main(){ int i; int i; return 0; } ``` Once declared and defined a variable, it is tied to its memory-box (in its lifetime, or scope, something we will talk about more later). But you can of course reassign it, after assigning a value to a defined variable: ```cpp #include using namespace std; int main(){ int i = 7; i = 11; i = 67; cout << i; return 0; } ``` ### Assignment `=`. The operator `=` is called the **assignment operator**. It **does not test for equality**. Rather, when we write `X = E`, where `X` is a variable, and `E` is some expression, this means: Update the value of `X` with the value *after* we evaluated the expression `E`. **What's on the left and right of `=` matters!!!** **Again, `X = E` means evaluate `E` first, then update `X` with the value found by `E`.** That is, determine whatever final value `E` gives you at the end, and then update the memory-box with identifier `X` with that final value. We can read `X = E` as: Assign to `X` the value of `E`. **Example A.** Let us work through this example. **We want to understand what is happening and be able to predict the output** . ```cpp #include using namespace std; int main() { int i, j, k; i = 1; j = 2; k = 3; cout << i << " " << j << " " << k << endl; i = j; cout << i << " " << j << " " << k << endl; j = i + k; cout << i << " " << j << " " << k << endl; k = j + k; cout << i << " " << j << " " << k << endl; return 0; } ``` Draw a cartoon diagram to aid your analysis! ### Naming variables. The name, or more correctly **identifier** can *start* with a letter `a-z` or `A-Z` or underscore `_` (**first character rule**), and *followed* by more letters `a-z, A-Z`, underscore `_`, or numbers `0-9`. **No special characters** like space ` `, `!`, `@`, `#`, `-`, `=`, etc. It is **case sensitive**, that `v` is not the same as `V`! Finally, you **cannot** name it with reserved C++ keywords like `int`, `return`, `using`, `namespace`. However, feel free to name it like `my_int`. There are several style of naming variables, just be clear and consistent. Some styles: - underscore style: `my_coffee_temperature` - lower camel case: `myCoffeeTemperature` - upper camel case: `MyCoffeeTemperature` Often, if a variable is to be a **constant**, then a convention is to use all upper case mixed with underscore, like `SCREEN_WIDTH`. ## The type `int` ### The operations `+`, `-`, and `*` with `int`, as well as `(` and `)`. Variables of type `int` (which represent integers, whole numbers) can be added with `+`, subtracted with `-`, and multiplied with `*`. Using them with these operations `+`, `-`, `*` does not affect the value of the variable, as we did not use assign `=`. Like in PEMDAS, order of operations is important, and you can use parenthesis `(` and `)` to elevate precedence like in math. **Example B.** Predict the output of the following: ```cpp #include using namespace std; int main(){ int x, y; x = 3; y = 4; cout << "We have x is " << x << " and y is " << y << endl; cout << "x + y is " << x + y << endl; cout << "x - y is " << x - y << endl; cout << "x * y is " << x * y << endl; cout << "x + x * y is " << x + x * y << endl; cout << "(x + x) * y is " << (x + x) * y << endl; cout << "After these calculations, we still have x is " << x << " and y is " << y << endl; x = x + 4; cout << "Since we performed x = x + 4, the new value of x is " << x; return 0; } ``` Here you can find the precedence order of these operators: [https://en.cppreference.com/cpp/language/operator_precedence](https://en.cppreference.com/cpp/language/operator_precedence) ### The operator `+=`, `-=`, and `*=`. If `X` is initialized as an `int`, and `E` is an expression, then `X += E` evaluates `E`, adds its value to `X`, update the result in `X`, and yields `X` (as an lvalue, to be technical) holding the new value. `+=` is called **addition assignment**. - Using the box model analogy, **first we increment the content of `X` by whatever `E` evaluates to, then we give back the box.** `X -= E` (**subtraction assignment**) and `X *= E` (**multiplication assignment**) work the same way with subtraction and multiplication, by replacing the word add above. In short, - `X += E` amounts to first do `X = X + E`, then give back the box. - `X -= E` amounts to first do `X = X - E`, then give back the box. - `X *= E` amounts to first do `X = X * E`, then give back the box. **Example C.** Predict the output of the following: ```cpp #include using namespace std; int main(){ int x = 3; int y = 4; cout << "x is now: " << x << endl; x += 4; cout << "x is now: " << x << endl; y *= x + 100; cout << "y is now: " << y << endl; // Below are some advanced examples. Do not sweat this. x -= 2 + (x += 7); cout << "x is now: " << x << endl; (y += 3) -= (x *= 2); cout << "Finally, x is " << x << endl; cout << "And y is " << y << endl; return 0; } ``` --- We ended here in class on Wednesday. Please continue to read the book **Section 5**. Read about the operators `++`, `/` and `%` for `int` (going to be useful), taking user input with `cin`, `double`, implicit casting, finding useful functions and include their relevant header files.